package com.x.Part7_创建线程的新方式.Callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * ClassName: CallableTest
 * Package: IntelliJ IDEA
 * Description:
 * 与之前的方式的对比：与Runnable方式的对比的好处:
 * call()可以有返回值，更灵活
 * call()可以使用throws的方式处理异常，更灵活
 * Callable使用了泛型参数，可以指明具体的call()的返回值类型，更灵活
 * 缺点:
 * 如果在主线程中需要获取分线程ca11()的返回值，则此时的主线程是阻塞状态的
 * Written by HanXu
 * Create 2024.03.28 17:47
 */
public class CallableTest {
    public static void main(String[] args) {

        NumThread num = new NumThread();
        FutureTask ft = new FutureTask(num);
        Thread t1 = new Thread(ft);
        t1.start();

        try {
            Integer sum = (Integer) ft.get();
            System.out.println("sum: "+sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class NumThread implements Callable{
    @Override
    public Object call() throws Exception {

        int sum = 0;
        for(int i=0; i<10; i++){
            sum += i;
            System.out.println(sum);
            Thread.currentThread().sleep(1000);
        }
        return sum;
    }
}
